<script setup>
import { apiGetSort, apiPublishArticle } from '@/api/forum.js';
import { onLoad,onShow } from '@dcloudio/uni-app';
import { ref } from 'vue';
import { storeToRefs } from "pinia";
import { useUserStore } from "@/store/user.js";
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const authorId = userInfo.value.id;
onLoad(async () => {
  await getSort();
});
//文章封面
const coverImage = ref('');
//一级标题
const title = ref('');
//二级标题
// const subtitle = ref('');
//富文本编辑器内容
const editorCtx = ref(null);
// 富文本编辑器内容
const contentHtml = ref('');
//小工具状态
const showMiniToolbar = ref(false);
//分类相关
const sortId1 = ref(null);
const sortList1 = ref([]);

const sortId2 = ref(null);
const sortList2 = ref([]);

const sortId3 = ref(null);
const sortList3 = ref([
  {value:1,text:'速成'},
  {value:2,text:'精讲'}, 
  {value:3,text:'入门'},
  {value:4,text:'复习'},
  {value:5,text:'进阶'},
  {value:6,text:'技巧'}
]);

//获取一级分类
const getSort = async (data = {}) => {
  const res = await apiGetSort();
  sortList1.value = res.map((item) => ({
    value: item.sortId1,
    text: item.name
  }));
  console.log('sortList1', sortList1.value);
  console.log('okokokoko');

};

//点击一级分类
const changeSort1 = async (e) => {
  console.log('change', e);
  sortList2.value = [];
  sortId2.value = null; // 重置v-model绑定的值
  if (!e) {
    return;
  }
  const res = await apiGetSort({ sortId1: e });
  sortList2.value = res.map((item) => {
    return {
      value: item.sortId2,
      text: item.name
    };
  });
};
///点击二级分类
const changeSort2 = (e) => {
  console.log('change', e);
};
//点击三级分类
const changeSort3 = (e) => {
  console.log('change', e);
};
const onEditorReady = () => {
  uni
    .createSelectorQuery()
    .select('#editor')
    .context((res) => {
      editorCtx.value = res.context;
    })
    .exec();
};

const onEditorInput = (e) => {
  contentHtml.value = e.detail.html;
};

// 切换小工具栏
const toggleMiniToolbar = () => {
  showMiniToolbar.value = !showMiniToolbar.value;
};

// 富文本操作
const setBold = () => {
  editorCtx.value.format('bold');
};

const setItalic = () => {
  editorCtx.value.format('italic');
};

// 插入图片
const insertImage = () => {
  uni.chooseImage({
    count: 1,
    success: async (chooseRes) => {
      const filePath = chooseRes.tempFilePaths[0];
      const compressRes = await uni.compressImage({ src: filePath, quality: 50 });
      const uploadRes = await uploadImage(compressRes.tempFilePath);
      if (uploadRes) {
        editorCtx.value.insertImage({
          src: uploadRes,
          alt: '文章图片'
        });
      }
    }
  });
};

const uploadImage = (filePath) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: 'http://8.146.206.32:8080/image/upload',
      filePath,
      name: 'image',
      formData: {
        fileName: Date.now() + '.png',
        fileType: 'article'
      },
      success: (res) => {
        const data = JSON.parse(res.data);
        if (data.code === 1) resolve(data.data);
        else uni.showToast({ title: '上传失败', icon: 'none' });
      },
      fail: (err) => {
        console.error('上传失败', err);
        uni.showToast({ title: '上传失败', icon: 'none' });
        reject();
      }
    });
  });
};

//封面图片
// 封面图片上传
const handleImageSelect = (files) => {
  // 1. 获取原始图片临时路径
  const originalTempPath = files.tempFilePaths[0];
  if (!originalTempPath) {
    console.error('未获取到图片路径');
    return;
  }

  // 2. 压缩图片（质量50%）
  uni.compressImage({
    src: originalTempPath, // 原始图片路径
    quality: 50, // 压缩质量（0-100，这里设为50%）
    success: (compressRes) => {
      // 3. 压缩成功后，获取压缩后的临时路径
      const compressedTempPath = compressRes.tempFilePath;
      if (!compressedTempPath) {
        console.error('图片压缩失败，未获取到压缩后路径');
        return;
      }

      // 4. 使用压缩后的路径上传
      uploadCompressedImage(compressedTempPath);
    },
    fail: (err) => {
      console.error('图片压缩失败', err);
      uni.showToast({ title: '图片压缩失败', icon: 'none' });
    }
  });
};
// 封装上传逻辑（使用压缩后的图片路径）
const uploadCompressedImage = (compressedTempPath) => {
  uni.uploadFile({
    url: 'http://8.146.206.32:8080/image/upload',
    filePath: compressedTempPath, // 压缩后的路径
    name: 'image',
    formData: {
      fileName: Date.now() + '.png',
      fileType: 'article'
    },
    success: (uploadRes) => {
      console.log('上传成功', JSON.parse(uploadRes.data).data);
      coverImage.value = JSON.parse(uploadRes.data).data;
      uni.showToast({ title: '上传成功', icon: 'success' });
    },
    fail: (err) => {
      console.error('上传失败', err);
      uni.showToast({ title: '上传失败，请重试', icon: 'none' });
    }
  });
};
// 选择图片失败处理
const handleSelectError = (err) => {
  console.error('选择图片失败', err);
  uni.showToast({ title: '选择图片失败', icon: 'none' });
};

// 上传文章
const getHtml = async () => {
  if (!title.value.trim()) return uni.showToast({ title: '请输入标题', icon: 'none' });
  if (!sortId1.value || !sortId2.value || !sortId3.value) return uni.showToast({ title: '请选择分类', icon: 'none' });
  editorCtx.value.getContents({
    success: async (result) => {
      console.log('文章HTML内容：', result.html);
      contentHtml.value = result.html;
    },
  });
  
  const res = await apiPublishArticle({
    authorId,
    title1: title.value,
    // title2: subtitle.value,
    coverImage: coverImage.value,
    content: contentHtml.value,
    sortId1: sortId1.value,
    sortId2: sortId2.value,
    sortId3: sortId3.value
  });
  console.log('文章上传params', {
    authorId,
    title1: title.value,
    // title2: subtitle.value,
    coverImage: coverImage.value,
    content: contentHtml.value,
    sortId1: sortId1.value,
    sortId2: sortId2.value,
    sortId3: sortId3.value
  });
  if (res.id) {
    uni.showToast({ title: '发布成功', icon: 'success' });
    setTimeout(()=>{
      uni.switchTab({
        url:"/pages/forum/forum"
      })
    },1000)
  } else {
    uni.showToast({ title: res.msg || '发布失败', icon: 'none' });
  }
};
</script>

<template>
  <view class="article-edit">
    <!-- 封面上传 -->
    <view class="coverImage">
      <!-- 前端组件：选择图片后自动触发上传 -->
      <uni-file-picker class="cover-picker" limit="1" title="上传封面" @select="handleImageSelect" @error="handleSelectError"></uni-file-picker>
    </view>

    <!-- 标题、分类输入 -->
    <view class="form-box">
      <input v-model="title" class="title-input" placeholder="请输入主标题" />
      <!-- <input v-model="subtitle" class="subtitle-input" placeholder="请输入副标题（选填）" /> -->
      <uni-data-select placeholder="请选择一级分类" v-model="sortId1" :localdata="sortList1" @change="changeSort1"></uni-data-select>
      <uni-data-select placeholder="请选择二级分类" v-model="sortId2" :localdata="sortList2" @change="changeSort2"></uni-data-select>
      <uni-data-select placeholder="请选择三级分类" v-model="sortId3" :localdata="sortList3" @change="changeSort3"></uni-data-select>
    </view>

    <!-- 富文本编辑器 -->
    <view class="editor-wrapper">
      <editor id="editor" class="editor" placeholder="在这里输入正文，可使用快捷键加粗、斜体等格式" @ready="onEditorReady" @input="onEditorInput"></editor>
    </view>

    <!-- 悬浮工具栏 -->
    <view class="float-toolbar">
      <!-- 打开富文本小工具栏 -->
      <button class="float-btn" @click="toggleMiniToolbar">
        <uni-icons type="compose" size="22" color="#fff"></uni-icons>
      </button>

      <button class="float-btn" @click="insertImage">
        <uni-icons type="image" size="22" color="#fff"></uni-icons>
      </button>
      <!-- 上传 -->
      <button class="float-btn" @click="getHtml">
        <uni-icons type="upload" size="22" color="#fff"></uni-icons>
      </button>
    </view>

    <!-- 小型富文本工具栏 -->
    <transition name="fade">
      <view v-if="showMiniToolbar" class="mini-toolbar">
        <button class="mini-btn" @click="setBold">B</button>
        <button class="mini-btn italic" @click="setItalic">I</button>
      </view>
    </transition>
  </view>
</template>


<style lang="scss" scoped>
.article-edit {
  padding: 40rpx 28rpx 100rpx;
  background-color: #f7f8fa;
  min-height: 100vh;

  .coverImage {
    margin-bottom: 40rpx;

    .cover-picker {
      background: #fff !important;
      border-radius: 20rpx;
      box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
      padding: 30rpx;
    }
  }

  .form-box {
    display: flex;
    flex-direction: column;
    gap: 24rpx;
    margin-bottom: 40rpx;

    input {
      background: transparent;
      padding: 20rpx 10rpx;
      border: none;
      border-bottom: 2rpx solid rgba(0, 0, 0, 0.05);
      font-size: 30rpx;
      outline: none;
      transition: all 0.2s;

      &:focus {
        border-color: #4fc08d;
      }

      &::placeholder {
        color: #bbb;
      }
    }
  }

  .editor-wrapper {
    background: #fff;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;
    margin-bottom: 80rpx;

    .editor {
      min-height: 500rpx;
      padding: 30rpx;
      font-size: 28rpx;
      color: #333;
      line-height: 1.8;
    }
  }

  /* 悬浮按钮组 */
  .float-toolbar {
    position: fixed;
    left: 50%;
    bottom: 30rpx;
    transform: translateX(-50%);
    display: flex;
    // flex-direction: column;
    gap: 20rpx;

    .float-btn {
      width: 90rpx;
      height: 90rpx;
      border-radius: 50%;
      background: linear-gradient(135deg, #4fc08d, #42b883);
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.15);
      transition: all 0.25s ease;

      &:active {
        transform: scale(0.92);
      }

      &:nth-child(2) {
        background: linear-gradient(135deg, #10b981, #059669);
      }

      &:nth-child(3) {
        background: linear-gradient(135deg, #3b82f6, #2563eb);
      }
    }
  }

  /* 小型富文本工具栏 */
  .mini-toolbar {
    position: fixed;
    left: 50%;
    bottom: 150rpx;
    transform: translateX(-50%);
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    display: flex;
    gap: 12rpx;
    padding: 12rpx 20rpx;
    z-index: 1000;

    .mini-btn {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      background: #4fc08d;
      color: #fff;
      font-weight: bold;
      font-size: 30rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s ease;

      &.italic {
        font-style: italic;
      }

      &:active {
        transform: scale(0.9);
      }
    }
  }

  /* 淡入淡出动画 */
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.25s;
  }
  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
  }
}
</style>
